<?php namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Services\AdminManager;
use App\User;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Hash;
use Auth;

class AuthController extends Controller
{
    public function signInAdmin(Request $request){
        $username = $request->get('username');
        $password = $request->get('password');

        $admin = AdminManager::signInByUsername($username,$password,1);

        if(!$admin){
            return response()->json(['level'=>'error','message'=>'帐号或密码错误！']);
        }

        return response()->json(['level'=>'success','message'=>trans("登录成功！"),'data'=>$admin]);
    }

    public function changePassword(Guard $guard,Request $request)
    {
        if(Auth::guard('admin')->guest()){
            return response()->json(["level"=>"error","message"=>"不允许访问"]);
        }

        /** @var User $user */
        $user = Auth::guard('admin')->user();

        $oldPassword = $request->get('oldpassword');
        $newpassword = $request->get('newpassword');

        if(!Hash::check($oldPassword,$user->password))
            return response()->json(['level'=>'error','message'=>'旧密码不匹配！']);

        $user->password = bcrypt($newpassword);
        $user->save();

        $guard->logout();

        return response()->json(['level'=>'success','message'=>trans("密码修改成功！")]);
    }

    public function signOut(Guard $guard){

        Auth::guard('admin')->logout();

        return redirect()->route("Admin.Home.login");
    }
}